<template>
  <div class="login-page">
    <div class="login-shell">
      <div class="login-showcase">
        <span class="login-showcase__badge">排课管理系统</span>
        <h1 class="login-showcase__title">欢迎登录</h1>
        <p class="login-showcase__desc">
          统一的教学排课一站式平台，为师生提供实时课程信息与便捷的角色入口。
        </p>
        <ul class="login-showcase__list">
          <li>实时课表与通知同步</li>
          <li>多角色智能化管理</li>
          <li>安全稳定的登录体验</li>
        </ul>
      </div>
      <el-card class="login-card" shadow="hover">
        <div class="login-card__header">
          <h2 class="login-card__title">账户登录</h2>
          <p class="login-card__subtitle">请选择身份类型完成登录</p>
        </div>
        <el-tabs v-model="activeTab" class="login-tabs" stretch>
          <el-tab-pane label="学生登录" name="student">
            <el-form ref="studentFormRef" :model="studentForm" :rules="studentRules" label-width="120px" class="login-form" autocomplete="off">
              <el-form-item label="学号" prop="stuNo">
                <el-input v-model="studentForm.stuNo" placeholder="请输入学号" autocomplete="off" name="student-username" />
              </el-form-item>
              <el-form-item label="身份证后六位" prop="idTail6">
                <el-input v-model="studentForm.idTail6" placeholder="请输入身份证后六位" maxlength="6" show-password autocomplete="new-password" name="student-password" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="full" :loading="loading" @click="handleStudentLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="教师登录" name="teacher">
            <el-form ref="teacherFormRef" :model="teacherForm" :rules="teacherRules" label-width="120px" class="login-form" autocomplete="off">
              <el-form-item label="教师工号" prop="teacherNo">
                <el-input v-model="teacherForm.teacherNo" placeholder="请输入教师工号" autocomplete="off" name="teacher-username" />
              </el-form-item>
              <el-form-item label="身份证后六位" prop="idTail6">
                <el-input v-model="teacherForm.idTail6" placeholder="请输入身份证后六位" maxlength="6" show-password autocomplete="new-password" name="teacher-password" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="full" :loading="loading" @click="handleTeacherLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="管理员登录" name="admin">
            <el-form ref="adminFormRef" :model="adminForm" :rules="adminRules" label-width="120px" class="login-form">
              <el-form-item label="管理员编号" prop="adminNo">
                <el-input v-model="adminForm.adminNo" placeholder="请输入管理员编号" />
              </el-form-item>
              <el-form-item label="密码" prop="adminPassword">
                <el-input v-model="adminForm.adminPassword" placeholder="请输入密码" type="password" show-password />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="full" :loading="loading" @click="handleAdminLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { studentLogin, teacherLogin, adminLogin } from '../api/auth'

const emit = defineEmits(['login-success'])

const activeTab = ref('student')
const loading = ref(false)

const studentFormRef = ref()
const teacherFormRef = ref()
const adminFormRef = ref()

const studentForm = reactive({ stuNo: '', idTail6: '' })
const teacherForm = reactive({ teacherNo: '', idTail6: '' })
const adminForm = reactive({ adminNo: '', adminPassword: '' })

const id6Validator = (rule, value, callback) => {
  if (!/^[0-9A-Za-z]{6}$/.test(value)) {
    callback(new Error('请输入6位字母或数字'))
  } else {
    callback()
  }
}

const studentRules = {
  stuNo: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  idTail6: [{ required: true, validator: id6Validator, trigger: 'blur' }]
}

const teacherRules = {
  teacherNo: [{ required: true, message: '请输入教师工号', trigger: 'blur' }],
  idTail6: [{ required: true, validator: id6Validator, trigger: 'blur' }]
}

const adminRules = {
  adminNo: [{ required: true, message: '请输入管理员编号', trigger: 'blur' }],
  adminPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleStudentLogin = async () => {
  const valid = await studentFormRef.value.validate()
  if (!valid) return
  
  console.group('🎓 学生登录流程')
  console.log('表单数据:', studentForm)
  
  loading.value = true
  try {
    const res = await studentLogin(studentForm)
    console.log('登录响应:', res)
    
    if (res && res.data) {
      const user = res.data
      console.log('用户信息:', user)
      
      const token = user.stuNo || user.studentId || 'local-token'
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('role', 'student')
      
      ElMessage.success('学生登录成功')
      emit('login-success')
    } else {
      console.warn('登录响应数据为空:', res)
      ElMessage.warning('登录失败：响应数据为空')
    }
  } catch (error) {
    console.error('学生登录异常:', error)
    ElMessage.error(`学生登录失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
    console.groupEnd()
  }
}

const handleTeacherLogin = async () => {
  const valid = await teacherFormRef.value.validate()
  if (!valid) return
  
  console.group('👨‍🏫 教师登录流程')
  console.log('表单数据:', teacherForm)
  
  loading.value = true
  try {
    const res = await teacherLogin(teacherForm)
    console.log('登录响应:', res)
    
    if (res && res.data) {
      const user = res.data
      console.log('用户信息:', user)
      
      const token = user.teNo || user.teacherId || 'local-token'
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('role', 'teacher')
      
      ElMessage.success('教师登录成功')
      emit('login-success')
    } else {
      console.warn('登录响应数据为空:', res)
      ElMessage.warning('登录失败：响应数据为空')
    }
  } catch (error) {
    console.error('教师登录异常:', error)
    ElMessage.error(`教师登录失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
    console.groupEnd()
  }
}

const handleAdminLogin = async () => {
  const valid = await adminFormRef.value.validate()
  if (!valid) return
  
  console.group('👨‍💼 管理员登录流程')
  console.log('表单数据:', adminForm)
  
  loading.value = true
  try {
    const res = await adminLogin(adminForm)
    console.log('登录响应:', res)
    
    if (res) {
      // 兼容多种后端返回结构：
      // 1) { token, user: { adminNo, ... } }
      // 2) { user: {...} }
      // 3) { data: { token, user } }
      // 4) 直接返回管理员实体 { adminId, adminNo, ... }
      const root = res.data && (res.data.user || res.data.token) ? res.data : res
      const userCandidate = root.user || (root.adminNo || root.adminName ? root : {})
      const token = root.token || res.token || userCandidate.adminNo || 'local-token'

      console.log('解析后的用户信息:', userCandidate)
      console.log('生成的Token:', token)

      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(userCandidate || {}))
      localStorage.setItem('role', 'admin')
      
      ElMessage.success('管理员登录成功')
      emit('login-success')
    } else {
      console.warn('登录响应数据为空:', res)
      ElMessage.warning('登录失败：响应数据为空')
    }
  } catch (error) {
    console.error('管理员登录异常:', error)
    ElMessage.error(`管理员登录失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
    console.groupEnd()
  }
}

// 切换标签时清空对应表单，避免浏览器自动填充残留
watch(activeTab, (tab) => {
  if (tab === 'student') {
    studentForm.stuNo = ''
    studentForm.idTail6 = ''
  } else if (tab === 'teacher') {
    teacherForm.teacherNo = ''
    teacherForm.idTail6 = ''
  }
})

// 检查后端连接状态
const checkBackendConnection = async () => {
  try {
    console.log('🔍 检查后端连接状态...')
    const response = await fetch('/api/admin/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ adminNo: 'test', adminPassword: 'test' })
    })
    console.log('后端连接状态:', response.status, response.statusText)
    return response.status !== 404
  } catch (error) {
    console.error('后端连接检查失败:', error)
    return false
  }
}

// 页面首次加载时清空学生/教师表单
onMounted(async () => {
  studentForm.stuNo = ''
  studentForm.idTail6 = ''
  teacherForm.teacherNo = ''
  teacherForm.idTail6 = ''
  
  // 检查后端连接
  const isConnected = await checkBackendConnection()
  if (!isConnected) {
    ElMessage.warning('后端服务连接异常，请检查服务是否启动')
  }
})
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  background:
    radial-gradient(circle at 15% 20%, rgba(102, 126, 234, 0.35), transparent 55%),
    radial-gradient(circle at 85% 15%, rgba(118, 75, 162, 0.32), transparent 50%),
    linear-gradient(135deg, #edf1ff 0%, #f5f7ff 100%);
}

.login-shell {
  display: grid;
  grid-template-columns: minmax(260px, 360px) minmax(320px, 420px);
  gap: 48px;
  align-items: stretch;
  width: 100%;
  max-width: 960px;
}

.login-showcase {
  position: relative;
  padding: 48px 40px;
  border-radius: 28px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.95) 0%, rgba(118, 75, 162, 0.95) 100%);
  color: #ffffff;
  box-shadow: 0 32px 80px -32px rgba(72, 83, 180, 0.6);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.login-showcase__badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.18);
  font-size: 13px;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  font-weight: 600;
}

.login-showcase__title {
  margin: 0;
  font-size: 36px;
  font-weight: 700;
}

.login-showcase__desc {
  margin: 0;
  font-size: 16px;
  line-height: 1.7;
  color: rgba(255, 255, 255, 0.85);
}

.login-showcase__list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 12px;
  font-size: 15px;
}

.login-showcase__list li {
  display: flex;
  align-items: center;
  gap: 10px;
}

.login-showcase__list li::before {
  content: '';
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
}

.login-card {
  width: 100%;
  border-radius: 24px;
  border: none;
  box-shadow: 0 24px 60px -28px rgba(43, 60, 125, 0.32);
}

.login-card :deep(.el-card__body) {
  padding: 36px 40px 40px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.login-card__header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.login-card__title {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #1f2d3d;
}

.login-card__subtitle {
  margin: 0;
  font-size: 14px;
  color: #596b90;
}

.login-tabs {
  margin-top: 4px;
}

.login-tabs :deep(.el-tabs__header) {
  margin-bottom: 16px;
}

.login-tabs :deep(.el-tabs__item) {
  font-weight: 600;
  color: #5c6789;
  padding: 0 16px;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #5a6fff;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  height: 3px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 12px;
  border: 1px solid rgba(116, 128, 156, 0.18);
  transition: all 0.3s ease;
  padding: 0 14px;
}

.login-form :deep(.el-input__wrapper:hover),
.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #6a7bff;
  box-shadow: 0 0 0 4px rgba(106, 123, 255, 0.1);
}

.full {
  width: 100%;
  border-radius: 12px;
  padding: 12px 0;
  font-weight: 600;
  letter-spacing: 0.02em;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.full:hover {
  background: linear-gradient(135deg, #7a8cff 0%, #8c5ed8 100%);
}

@media (max-width: 960px) {
  .login-shell {
    grid-template-columns: 1fr;
  }

  .login-showcase {
    padding: 40px 32px;
  }

  .login-card :deep(.el-card__body) {
    padding: 32px;
  }
}

@media (max-width: 540px) {
  .login-page {
    padding: 32px 16px;
  }

  .login-showcase__title {
    font-size: 30px;
  }

  .login-card :deep(.el-card__body) {
    padding: 28px 24px 32px;
  }

  .login-form :deep(.el-form-item__label) {
    width: 88px !important;
  }
}
</style>





